package com.ruicar.afs.cloud.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.admin.api.dto.PassWordRule;
import com.ruicar.afs.cloud.admin.api.dto.SysParamDto;
import com.ruicar.afs.cloud.admin.entity.*;
import com.ruicar.afs.cloud.admin.enums.SysParamChange;
import com.ruicar.afs.cloud.admin.enums.SysParamType;
import com.ruicar.afs.cloud.admin.service.SysParamInfoService;
import com.ruicar.afs.cloud.common.core.auditlog.util.AuditLogUtils;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.log.vo.AuditLogWrapper;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.components.datadicsync.SysParamHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

@RestController
@AllArgsConstructor
@RequestMapping("/sysparam")
@Api(value = "sysparam", description = "平台参数维护")
@Slf4j
public class SysParamController {
    private final SysParamInfoService sysParamInfoService;
    @PostMapping("/page")
    @ApiOperation(value = "获取平台参数")
    public IResponse<Object> listParamInfo(@RequestBody QueryCondition<SysParamDto> condition){
        IPage iPage  =sysParamInfoService.page(new Page<>(condition.getPageNumber(),condition.getPageSize()),
                Wrappers.<SysParamInfo>lambdaQuery()
                        .eq(StringUtils.isNotEmpty(condition.getCondition().getParamKey()),SysParamInfo::getParamKey,condition.getCondition().getParamKey())
                        .like(StringUtils.isNotEmpty(condition.getCondition().getParamDesc()),SysParamInfo::getParamDesc,condition.getCondition().getParamDesc()));
        return IResponse.success(iPage);
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存平台参数")
    @PreAuthorize("@pms.hasPermission('afs_sys_param_modify')")
    public IResponse save(@Valid @RequestBody SysParamInfo sysParamInfo){
        if(sysParamInfo.getId()==null){
            if(sysParamInfoService.count(Wrappers.<SysParamInfo>lambdaQuery().eq(SysParamInfo::getParamKey,sysParamInfo.getParamKey()))>0){
                return IResponse.fail("key是"+sysParamInfo.getParamKey()+"已存在");
            }else{
               sysParamInfoService.save(sysParamInfo);
            }
        }else{
            SysParamInfo dbInfo = sysParamInfoService.getById(sysParamInfo.getId());
            if(dbInfo==null){
                return IResponse.fail("数据错误");
            }
            if(dbInfo.getChangeAble()== SysParamChange.NO){
                return IResponse.fail("key是"+sysParamInfo.getParamKey()+"不能修改");
            }
            AuditLogUtils.doAudit(AuditLogWrapper.builder().changeIndex(sysParamInfo.getParamKey()).changeReason("").oldObject(dbInfo).newObject(sysParamInfo).currentUserName(SecurityUtils.getUsername()).build());
            sysParamInfoService.updateById(sysParamInfo);
        }
        sysParamInfoService.publishParamDataToSync();
        return IResponse.success(Boolean.TRUE).setMsg("操作成功");
    }
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除参数")
    @PreAuthorize("@pms.hasPermission('afs_sys_param_del')")
    public IResponse delete(@PathVariable Long id){
        SysParamInfo dbInfo = sysParamInfoService.getById(id);
        if(dbInfo==null){
            return IResponse.fail("数据错误");
        }
        if(dbInfo.getChangeAble()== SysParamChange.NO){
            return IResponse.fail("key是"+dbInfo.getParamKey()+"不能修改");
        }
        sysParamInfoService.removeById(id);
        sysParamInfoService.publishParamDataToSync();
        return IResponse.success(Boolean.TRUE).setMsg("操作成功");
    }

    @GetMapping("/getPassRule")
    public IResponse<PassWordRule> getPassWordRule(){
        PassWordRule passWordRule = new PassWordRule();
        passWordRule.setMinLength((int)SysParamHelper.getLong(AfsEnumUtil.key(SysParamType.PASSWORD_MIN_LENGTH),6L));
        passWordRule.setMaxLength((int)SysParamHelper.getLong(AfsEnumUtil.key(SysParamType.PASSWORD_MAX_LENGTH),12L));
        passWordRule.setRules(Arrays.asList(SysParamHelper.getString(AfsEnumUtil.key(SysParamType.PASSWORD_BASE_RULE),"0").split(",")));
        return IResponse.success(passWordRule);
    }

    @GetMapping("/syncParams")
    public IResponse syncParams(){
        sysParamInfoService.publishParamDataToSync();
        return IResponse.success(Boolean.TRUE);
    }
}
